/*
 *
 * @ProjectName:    my_umi_app
 * @Package:
 * @ClassName:      upload
 * @Description:    上传
 * @Author:         SuPeiSen
 * @CreateDate:     2021/1/23 5:17 下午
 * @UpdateDate:     2021/1/23 5:17 下午
 * @UpdateRemark:   更新说明：
 * @Version:        1.0
 */

import { Requests } from '@/utils/requests';
import { ApiPath } from '@/config/api_config';
import { log } from '@/utils/app_fun';
import { QiNiuResponse, QiuToken } from '@/type/upload_type';
import { upload } from 'qiniu-js';
import { CompletionObserver } from 'qiniu-js/esm/observable.d';
import { UploadProgress } from 'qiniu-js/esm/upload/base.d';
import { Local, LocalKey } from '@/utils/cache';

// 获取七牛云上传token
export const getQiNiuUploadTokenApi = async () => {
  const qiNiuToken = Local.getStr(LocalKey.qiNiuToken);
  if (qiNiuToken != undefined) {
    return qiNiuToken;
  }
  log(null, '触发重新获取UploadToken');
  const model = await Requests.defaults.http<QiuToken>(
    'get',
    ApiPath.getQiNiuToken,
  );
  if (model.success) {
    const uploadToken = model.data!.data.uploadToken;
    Local.setStr(LocalKey.qiNiuToken, uploadToken, 7200);
    return uploadToken;
  }
  return undefined;
};

export const getFileNameByDate = () => {
  return Date.parse(Date()).toString();
};

interface ImageLocation {
  location: string;
}

// 上传文件到七牛云
export const uploadFileToQiNiuApi = async (
  blobFile: Blob,
  successFun: (url: string) => void,
  failFun: (
    err: string,
    options?: {
      remove?: boolean;
    },
  ) => void,
) => {
  const uploadToken = await getQiNiuUploadTokenApi();
  if (uploadToken !== undefined) {
    const file = new File([blobFile], '');
    const observable = upload(file, getFileNameByDate(), uploadToken);
    const callBack: CompletionObserver<
      UploadProgress,
      string,
      QiNiuResponse
    > = {
      next: (next) => {
        console.log(next.total.loaded);
      },
      error: (error) => {
        failFun(error);
      },
      complete: (res) => {
        console.log(res);
        successFun('http://blogimage.hellosu.top/' + res.data.key);
      },
    };
    observable.subscribe(callBack);
  }
};
